package com.nw.plungin;


import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class MongoManager {
	/**
	 * 由springboot自动注入，默认配置会产生mongoTemplate这个bean
	 */

	public static MongoClient mongo;
	
	/*public static MongoClient getMongo(){
		if (mongo==null) {
			ServerAddress serverAddress = new ServerAddress(ConfigConstant.MONGO_IP, ConfigConstant.MONGO_PORT);
			List<ServerAddress> addressList = new ArrayList<ServerAddress>();
			addressList.add(serverAddress);

			MongoCredential credential = MongoCredential.createScramSha1Credential(
					ConfigConstant.MONGO_USER, ConfigConstant.MONGO_DB, ConfigConstant.MONGO_PASSWORD
							.toCharArray());
			List<MongoCredential> credentialList = new ArrayList<MongoCredential>();
			credentialList.add(credential);

			MongoClient mongoClient = new MongoClient(addressList, credentialList);
			mongo = mongoClient;
			return mongo;
		}else {
			return mongo;
		}
	}*/
	public static void add(String collectionName,Map<String, Object> map,MongoTemplate mongoTemplate){
		MongoDatabase mongoDatabase = mongoTemplate.getDb();
	/*	MongoDatabase mongoDatabase = mongoTemplate.getDb();*/
		MongoCollection collection = mongoDatabase.getCollection(collectionName);
		Document doc = new Document(map);
		collection.insertOne(doc);
	}
	public static void addBatch(String collectionName,List<Map<String, Object>> list,MongoTemplate mongoTemplate){
		MongoDatabase mongoDatabase = mongoTemplate.getDb();
		MongoCollection collection = mongoDatabase.getCollection(collectionName);
		List<Document> docList = new ArrayList<Document>();
		for (Map<String, Object> map : list) {
			Document doc = new Document(map);
			docList.add(doc);
		}
		collection.insertMany(docList);
	}
	public static void update(String collectionName,Map<String, Object> query,Map<String, Object> map,MongoTemplate mongoTemplate){
		MongoDatabase mongoDatabase = mongoTemplate.getDb();
		MongoCollection collection = mongoDatabase.getCollection(collectionName);
		Document doc_query = new Document(query);
		Document doc_map = new Document(map);
		Document doc_update = new Document("$set",doc_map);
		collection.updateOne(doc_query, doc_update);
	}
	public static void delete(String collectionName,Map<String, Object> query,MongoTemplate mongoTemplate){
		MongoDatabase mongoDatabase = mongoTemplate.getDb();
		MongoCollection collection = mongoDatabase.getCollection(collectionName);
		Document doc_query = new Document(query);
		collection.deleteOne(doc_query);
	}
	
	//renwei_all_drug_search_no_repeat
	public static long queryCount(String collectionName,Map<String, Object> query,MongoTemplate mongoTemplate){
		MongoDatabase mongoDatabase = mongoTemplate.getDb();
		
		MongoCollection<Document> collection = mongoDatabase
				.getCollection(collectionName);
		Document doc_query = new Document(query);
		long count = collection.count(doc_query);
		return count;
	}
	public static Document queryOne(String collectionName,Map<String, Object> query,MongoTemplate mongoTemplate){
		MongoDatabase mongoDatabase = mongoTemplate.getDb();
		MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
		Document doc_query = new Document(query);
		FindIterable<Document> findIterable = collection.find(doc_query);
//		List<Document> list = new ArrayList<Document>();
		MongoCursor<Document> mongoCursor = findIterable.iterator();
		Document d = null;
		while (mongoCursor.hasNext()) {
			d = mongoCursor.next();
			break;
		}
		return d;
	}
	public static List<Document> query(String collectionName,Map<String, Object> query,Map<String, Object> sort,int skip,int limit,MongoTemplate mongoTemplate){
		MongoDatabase mongoDatabase = mongoTemplate.getDb();
		
		MongoCollection<Document> collection = mongoDatabase
		.getCollection(collectionName);
		// 检索所有文档
		/**
		 * 1. 获取迭代器FindIterable<Document> 2. 获取游标MongoCursor<Document> 3.
		 * 通过游标遍历检索出的文档集合
		 * */
		Document doc_query = new Document(query);
		/**
		 * collection.find(
    		new Document("stars", new Document("$gte", 2)
          .append("$lt", 5))
          .append("categories", "Bakery"))
          
          
          collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
                .sort(Sorts.ascending("name"))
                .forEach(printBlock);
		 */
		FindIterable<Document> findIterable = collection.find(doc_query);
		//排序
		if (sort!=null) {
			Document doc_sort = new Document(sort);
			findIterable.sort(doc_sort);
		}
		//分页
		if (limit>0) {
			findIterable.skip(skip).limit(limit);
		}else {
			
		}
		List<Document> list = new ArrayList<Document>();
		//1
//		Block<Document> printBlock = new Block<Document>() {
//		       @Override
//		       public void apply(final Document document) {
//		           System.out.println(document.toJson());
//		       }
//		};
//		findIterable.forEach(printBlock);
		//2
		//findIterable.batchSize(10);
		MongoCursor<Document> mongoCursor = findIterable.iterator();
		while (mongoCursor.hasNext()) {
			Document d = mongoCursor.next();
			list.add(d);
		}
//		mongoClient.close();//静态用一个，一直开启着
		return list;
	}
	public static List<Document> queryFields(String collectionName,Map<String, Object> query,Map<String, Object> sort,int skip,int limit,MongoTemplate mongoTemplate){
		MongoDatabase mongoDatabase = mongoTemplate.getDb();
		
		MongoCollection<Document> collection = mongoDatabase
				.getCollection(collectionName);
		// 检索所有文档
		/**
		 * 1. 获取迭代器FindIterable<Document> 2. 获取游标MongoCursor<Document> 3.
		 * 通过游标遍历检索出的文档集合
		 * */
		Document doc_query = new Document(query);
		/**
		 * collection.find(
    		new Document("stars", new Document("$gte", 2)
          .append("$lt", 5))
          .append("categories", "Bakery"))
          
          
          collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery")))
                .sort(Sorts.ascending("name"))
                .forEach(printBlock);
		 */
		FindIterable<Document> findIterable = collection.find(doc_query);
		//排序
		if (sort!=null) {
			Document doc_sort = new Document(sort);
			findIterable.sort(doc_sort);
		}
		//分页
		if (limit>0) {
			findIterable.skip(skip).limit(limit);
		}else {
			
		}
		List<Document> list = new ArrayList<Document>();
		//1
//		Block<Document> printBlock = new Block<Document>() {
//		       @Override
//		       public void apply(final Document document) {
//		           System.out.println(document.toJson());
//		       }
//		};
//		findIterable.forEach(printBlock);
		//2
		//findIterable.batchSize(10);
		MongoCursor<Document> mongoCursor = findIterable.iterator();
		while (mongoCursor.hasNext()) {
			Document d = mongoCursor.next();
			list.add(d);
		}
//		mongoClient.close();//静态用一个，一直开启着
		return list;
	}
	public static void main(String[] args) {
		Map<String, Object> query = new HashMap<String, Object>();
		Map<String, Object> query2 = new HashMap<String, Object>();
		query2.put("$regex", "豆");
//		query.put("name", "萘甲唑啉");
		query.put("name", query2);
		/*List<Document> list = query("renwei_all_drug_search_no_repeat",query,null,0,10, mongoTemplate);
		for (Document document : list) {
			System.out.println(document);
		}*/
	}

}
